/**
 * <p/>
 * 实现功能：国家
 * <p/>
 *
 * @author 李艳
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Button, Checkbox, Input, message, Modal} from 'antd';
import SimpleTable from "../../../commons/components/SimpleTable";
import {hide, show} from "../../../configs/SharedReducer";
import {deleteCorp, getAllSupplierUser, save} from "./SupplierUserService";
import SupplierUserModal from "./SupplierUserModal";
import SupplierUserConfigTabsView from "./SupplierUserConfigTabsView";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import PageOperateHoc from "../../../commons/components/PageOperateHoc";
import CheckAuth from "../../../commons/components/CheckAuth";

const Search = Input.Search;
const confirm = Modal.confirm;

class SupplierUserTable extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "供应商用户管理"}];
    this.state = {
      data: [],
      modalVisible: false,
      confirmLoading: false,
      selectedRows: [],
      isAdd: false,
      isPositionConfig: false,
      searchValue: ""
    };
  }

  componentWillMount() {
    this.getDataSource()
  }

  onRef = (ref) => {
    this.ref = ref
  };
  getDataSource = (params) => {
    this.props.show();
    getAllSupplierUser(params).then(data => {
      this.setState({data, selectedRows: []})
    }).catch(e => {
    }).finally(() => {
      this.props.hide();
    })
  };

  handleRowSelectChange = (selectedRows) => {
    this.setState({selectedRows})
  };
  handleModalVisible = (modalVisible, isAdd = this.state.isAdd) => {
    this.setState({modalVisible, isAdd})
  };
  addClick = () => {
    this.handleModalVisible(true, true)
  };
  editClick = (record) => {
    this.setState({editData: record});
    this.handleModalVisible(true, false)
  };
  handleSave = () => {
    this.ref.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let params = {}
        Object.assign(params, values);
        if (this.state.isAdd)
          delete params.id;//新增时id==="",保存会出错，需删除id
        this.setState({confirmLoading: true});
        save(params).then(result => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "请求成功");
            //刷新本地数据
            this.getDataSource({quickSearchValue: this.state.searchValue});
            this.setState({confirmLoading: false, modalVisible: false});
          } else {
            message.error(result.message ? result.message : "请求失败");
            this.setState({confirmLoading: false});
          }
        }).catch(e => {
          this.setState({confirmLoading: false});
        })
      }
    })
  };
  judgeSelected = () => {
    if (this.state.selectedRows.length === 0) {
      message.error("请选择一行数据！");
      return false
    }
    return true
  };

  handleModalCancel = () => {
    this.handleModalVisible(false)
  };

  handleSearch = (value) => {
    this.setState({searchValue: value});
    this.getDataSource({quickSearchValue: value})
  };

  deleteClick = (record) => {
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        let params = {};
        params = record.id;
        thiz.props.show();
        deleteCorp(params).then(result => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "请求成功");
            //刷新本地数据
            thiz.getDataSource({quickSearchValue: thiz.state.searchValue});
          } else {
            message.error(result.message ? result.message : "请求失败");
          }
        }).catch(e => {
        }).finally(() => {
          thiz.props.hide();
        })
      }
    });
  };
  onPositionConfigClick = () => {
    if (!this.judgeSelected()) return;
    this.setDisplay(true)
  };

  setDisplay = (display) => {
    this.setState({isPositionConfig: display})
  };
  getPathData = () => {
    const {isPositionConfig, selectedRows} = this.state;
    if (isPositionConfig) {
      const path = [{name: `配置用户【${selectedRows[0] ? selectedRows[0].name : ""}】`}];
      return [...this.initPath, ...path];
    } else {
      return "";
    }
  };
  getExtra = () => {
    const {isPositionConfig} = this.state;
    if (isPositionConfig) {
      return [
        <Button key={"return"} onClick={() => this.setDisplay(false)}>返回</Button>
      ]
    }
    return null;
  };

  render() {
    const columns = [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth operateCode="BASIC-YHGL-GYSYHGL-SAVE">
                <a className={'row-operator-item'} onClick={() => this.editClick(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth operateCode="BASIC-YHGL-GYSYHGL-DELETE">
                <a className={'row-operator-item'} onClick={() => this.deleteClick(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '账号',
        dataIndex: 'code',
        width: 120
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 240
      },
      {
        title: '供应商代码',
        dataIndex: 'supplierCode',
        width: 140
      },
      {
        title: '供应商名称',
        dataIndex: 'supplierName',
        width: 240
      },
      {
        title: '冻结',
        dataIndex: 'frozen',
        render: (text, record) => (
          <div style={{textAlign: "center"}}>
            <Checkbox checked={record.frozen === true} disabled/>
          </div>
        ),
      }
    ];

    const title = () => {
      return [
        <CheckAuth operateCode="BASIC-YHGL-GYSYHGL-SAVE" key='add'>
          <Button type={"primary"} key="edit" className={"primaryButton"}
                  onClick={this.addClick}>新增</Button>
        </CheckAuth>,
        <CheckAuth operateCode="BASIC-YHGL-GYSYHGL-CONFIG" key='config'>
          <Button key="config"
                  onClick={this.onPositionConfigClick}>配置</Button>
        </CheckAuth>,
      ]
    };

    //表头搜索框
    const search = () => {
      return [
        <Search
          key="search"
          placeholder="输入关键字查询"
          onSearch={value => this.handleSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };
    let path = this.getPathData();
    const {isPositionConfig} = this.state;
    return (
      <HeadBreadcrumb
        style={isPositionConfig ? {margin: 0, padding: 0, height: "100%"} : {}}
        pathData={this.getPathData()}
        rightExtra={this.getExtra()}
      >
        <div className={"tbar-table"} style={{display: this.state.isPositionConfig ? "none" : "block"}}>
          <div className={'tbar-box'}>
            <div className={'tbar-btn-box'}>{title()}</div>
            <div className={'tbar-search-box'}>{search()}</div>
          </div>
          <SimpleTable
            rowsSelected={this.state.selectedRows}
            onSelectRow={this.handleRowSelectChange}
            data={this.state.data}
            columns={columns}
          />
          <SupplierUserModal
            isAdd={this.state.isAdd}
            modalVisible={this.state.modalVisible}
            confirmLoading={this.state.confirmLoading}
            handleOk={this.handleSave}
            handleCancel={this.handleModalCancel}
            onRef={this.onRef}
            defaultValue={this.state.editData ? this.state.editData : {}}/>
        </div>
        {
          this.state.isPositionConfig ? <SupplierUserConfigTabsView
            userInfo={this.state.selectedRows[0] ? this.state.selectedRows[0] : {}}
            setDisplay={this.setDisplay}/> : null
        }
      </HeadBreadcrumb>
    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(SupplierUserTable))



